/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.jm.acionista.datamodel;

import br.jm.acionista.base.eao.EaoException;
import br.jm.acionista.entity.Moeda;
import br.jm.acionista.sistema.eao.MoedaEao;
import br.jm.acionista.view.MoedaBean;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.primefaces.model.LazyDataModel;

/**
 *
 * @author joao
 */
public class LazyMoedaDataModel extends LazyDataModel<Moeda> {

    private MoedaEao moedaJpa;
    private Moeda moeda;

    public LazyMoedaDataModel(MoedaEao moedaJpa) {
        this.moedaJpa = moedaJpa;
        setRowCount(moedaJpa.getCount("Moeda"));
    }

    
    public Moeda getRowData(String rowKey) {
        try {
            int nId = Integer.parseInt(rowKey);
            moeda = moedaJpa.getPorId(nId);
        } catch (EaoException ex) {
            Logger.getLogger(LazyMoedaDataModel.class.getName()).log(Level.SEVERE, null, ex);
        }
        return moeda;
    }

    public Object getRowKey(Moeda moeda) {
        String cId = null;
        if (moeda.getIdMoeda() != null) {
            cId = moeda.getIdMoeda().toString();
        }
        return cId;
    }

    
    public List<Moeda> load(int first, int pageSize, String sortField, boolean sortOrder, Map<String, String> filters) {
        List<Moeda> data = new ArrayList<Moeda>();

        try {
            data = moedaJpa.getNative("Moeda", first, pageSize, sortField, true, filters, null);
        } catch (Exception ex) {
            Logger.getLogger(MoedaBean.class.getName()).log(Level.SEVERE, null, ex);
        }

        //sort
        if (sortField != null) {
            Collections.sort(data, new LazySorter(sortField, sortOrder));
        }

        //rowCount
        int dataSize = data.size();
        this.setRowCount(dataSize);

        //paginate
        if (dataSize > pageSize) {
            try {
                return data.subList(first, first + pageSize);
            } catch (IndexOutOfBoundsException e) {
                return data.subList(first, first + (dataSize % pageSize));
            }
        } else {
            return data;
        }
    }
}